<template>
  <div class="main">
    <div class="form_content">
      <NScrollbar>
        <NSpin :show="spinShow">
          <div class="content">
            <NForm
              ref="formRef"
              :model="formValue"
              :rules="rules"
              label-placement="left"
              :label-width="115"
              label-align="right"
              require-mark-placement="left"
            >
              <NSpace>
                <NFormItem
                  label="证书编号:"
                  path="certificateNo"
                >
                  <NInput
                    v-model:value="formValue.certificateNo"
                    placeholder="输入证书编号"
                    style="width: 250px"
                  />
                </NFormItem>
                <NFormItem
                  label="藏家:"
                  path="collector"
                >
                  <NInput
                    v-model:value="formValue.collector"
                    placeholder="输入藏家"
                    style="width: 250px"
                  />
                </NFormItem>
              </NSpace>
              <NSpace>
                <NFormItem
                  label="经手人:"
                  path="handledBy"
                >
                  <NInput
                    v-model:value="formValue.handledBy"
                    placeholder="输入经手人"
                    style="width: 250px"
                  />
                </NFormItem>
                <NFormItem
                  label="捐赠数量:"
                  path="donateNum"
                >
                  <NInput
                    v-model:value="formValue.donateNum"
                    placeholder="输入捐赠数量"
                    style="width: 250px"
                  />
                </NFormItem>
              </NSpace>
              <NSpace>
                <NFormItem
                  label="捐赠内容:"
                  path="donateContent"
                >
                  <NInput
                    v-model:value="formValue.donateContent"
                    placeholder="输入捐赠内容"
                    style="width: 250px"
                  />
                </NFormItem>
                <NFormItem
                  label="所属批次:"
                  path="batchIds"
                >
                  <NSelect
                    :options="listOption"
                    v-model:value="formValue.batchIds"
                    placeholder="请选择所属批次"
                    clearable
                    style="width: 250px"
                    filterable
                    @update:value="valueChange"
                    multiple
                    @search="queryListOption"
                    :render-option="renderOption"
                  />
                </NFormItem>
              </NSpace>
              <NSpace>
                <NFormItem path="certificateTypeCode" label="证书类型:" >
                  <NSelect
                  :options="listOptionCer"
                  v-model:value="formValue.certificateTypeCode"
                  placeholder="请选择证书类型"
                  @update:value="valueChange1"
                  clearable
                  style="width: 250px;"
                />

          </NFormItem>
                <NFormItem
                  label="规格内容:"
                  v-if='formValue.certificateTypeCode=="A6103"'
                  path="certificateSpecs"
                >
                  <NInput
                    v-model:value="formValue.certificateSpecs"
                    placeholder="输入规格内容"
                    style="width: 250px"
                  />
                </NFormItem>
              </NSpace>
             
              <NSpace>
                <NFormItem
                  label="备注:"
                  path="notes"
                >
                  <NInput
                    v-model:value="formValue.notes"
                    placeholder="输入备注"
                    style="width: 630px"
                    type="textarea"
                  />
                </NFormItem>
              </NSpace>
              <NSpace>
                <NFormItem
                  label="附件:"
                  path="fileIds"
                >
                  <VUpload
                    :file-list="fileList"
                    @getList="handleUploadList"
                    style="width: 250px"
                  />
                </NFormItem>
              </NSpace>
            </NForm>
          </div>
        </NSpin>
      </NScrollbar>
    </div>
  </div>
  <FixedAction>
    <NSpace justify="center">
      <NButton
        style="width: 78px"
        ghost
        @click="goBack"
      >
        取消
      </NButton>
      <NButton
        type="primary"
        style="width: 78px"
        @click="confirm"
        :disabled="loading"
        :loading="loading"
      >
        保存
      </NButton>
    </NSpace>
  </FixedAction>
</template>

<script setup lang="ts">
import { ref, onMounted, type VNode, reactive, watch, h } from 'vue'
import {
  NSpace,
  NForm,
  NInput,
  NFormItem,
  NButton,
  NScrollbar,
  NSelect,
  useMessage,
  NSpin,
  NTooltip,
  type SelectOption
} from 'naive-ui'
import type { FormInst } from 'naive-ui'
import router from '@/router'
import { useTagStore } from '@/stores/layout'
import FixedAction from '@/components/FixedAction.vue'
import { sendRequest } from '@/utils/api'
import { useRoute } from 'vue-router'
import { keysOf } from '@/utils/object'
import VUpload from '@/views/OA/Common/Upload.vue'
import type { HttpResponse } from '@/utils/http'

const renderOption = ({ node, option }: { node: VNode; option: SelectOption }) =>
  h(NTooltip, null, {
    trigger: () => node,
    default: () => option.label
  })
const route = useRoute()
const tags = useTagStore().tags
const message = useMessage()
const loading = ref(false)
const formRef = ref<FormInst | null>(null)
const listOption = ref([])
const listOptionCer = ref([])
const formValue = reactive({
  certificateNo: '',
  collector: '',
  handledBy: '',
  donateNum: '',
  certificateTypeCode:'',
  certificateSpecs:'',
  donateContent: '',
  batchIds: [],
  fileIds: '',
  notes: ''
})
const fileList: any = ref([])
const rules = {
  certificateNo: {
    required: true,
    trigger: ['input', 'blur', 'change'],
    validator: (_: any, value: any) => {
      if (value.length == 0) return new Error('请输入证书编号')
      if (value.length > 15) return new Error('证书编号字数不得超过15')
      return true
    }
  },
  collector: {
    required: true,
    trigger: ['input', 'blur', 'change'],
    validator: (_: any, value: any) => {
      if (value.length == 0) return new Error('请输入藏家')
      if (value.length > 10) return new Error('藏家字数不得超过10')
      return true
    }
  },
  handledBy: {
    required: true,
    trigger: ['input', 'blur', 'change'],
    validator: (_: any, value: any) => {
      if (value.length == 0) return new Error('请输入经手人')
      if (value.length > 10) return new Error('经手人字数不得超过10')
      return true
    }
  },
  donateNum: {
    required: true,
    trigger: ['input', 'blur', 'change'],
    validator: (_: any, value: any) => {
      if (value.length == 0) return new Error('请输入捐赠数量')
      if (value.length > 5) return new Error('捐赠数量字数不得超过5')
      return true
    }
  },
  certificateTypeCode: {
    required: true,
    trigger: ['change', 'blur','input'],
    validator: (_: any, value: any) => {
      console.log(value)
      if (!value) return new Error('请选择证书类型')
      return true
    }
  },
  certificateSpecs: {
    required: true,
    trigger: ['change', 'blur','input'],
    validator: (_: any, value: any) => {
      if (!value&&formValue.certificateTypeCode=="A6103") return new Error('请输入其他规格')
      return true
    }
  },
  donateContent: {
    required: true,
    trigger: ['input', 'blur', 'change'],
    validator: (_: any, value: any) => {
      if (value.length == 0) return new Error('请输入捐赠内容')
      if (value.length > 30) return new Error('捐赠内容字数不得超过30')
      return true
    }
  },
  batchIds: {
    required: true,
    trigger: ['change', 'blur','input'],
    validator: (_: any, value: any) => {
      console.log(value)
      if (value.length==0) return new Error('请选择所属批次')
      return true
    }
  },
  notes: {
    required: false,
    trigger: ['input', 'blur', 'change'],
    validator: (_: any, value: any) => {
      if (value.length > 200) return new Error('备注字数不得超过200')
      return true
    }
  }
}
// 附件
const handleUploadList = (v: any) => (formValue.fileIds = v)
// 返回
const goBack = () => {
  const index = tags.findIndex((item: any) => item.path === router.currentRoute.value.fullPath)

  tags.splice(index, 1)
  if (tags.length == 0) {
    router.push({ path: '/OA/Workbench/UserDesktop' })
  } else history.back()
}
//所属批次下拉
const getFunction = async (v?: any) => {
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'baseDonateCertificate',
    api: 'listBatchOptions',
    override: {
      params: {
        batchName: v,
        id: route.params.id as never
      }
    }
  })
  if (error) return message.error(error.message)
  listOption.value = res.data
}
const getFunctionCer = async () => {
  listOptionCer.value = []
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'baseDonateCertificate',
    api: 'listByParentCode',
    override: {
      params: {
        dicCode: 'A61'
      }
    }
  })
  if (error) return message.error(error.message)
  res.data.forEach((i: any) => {
    // @ts-ignore
    listOptionCer.value.push({ label: i.dicName, value: i.dicCode })
  })
}
const queryListOption = (v: any) => {
  // console.log(v)
  getFunction(v)
}
//修改
const confirm = () => {
  formRef.value?.validate(async (err: any) => {
    if (err) return
    if(formValue.batchIds.length>0){
      // @ts-ignore
      formValue.batchIds=formValue.batchIds.join(',')
    }
    loading.value = true
    const [error, res] = await sendRequest<HttpResponse>({
      module: 'baseDonateCertificate',
      api: 'update',
      override: {
        data: {
          ...formValue
        }
      }
    })
    loading.value = false
    if (error) return message.error(error.message)
    message.success(res.msg)
    goBack()
  })
}
const valueChange=(v:any)=>{
  console.log(v)
  formValue.batchIds=v
}
const valueChange1=(v:any)=>{
  console.log(v)
  formValue.certificateSpecs=''
}
// 获取详情
const spinShow = ref(false)
const getDispatchInfo = async () => {
  spinShow.value = true
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'baseDonateCertificate',
    api: 'info',
    uri: {
      id: route.params.id as never
    }
  })
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  fileList.value = res.data.fileList
  keysOf(res.data).forEach((e) => {
    // @ts-ignore
    formValue[e] = res.data[e]
    if(e==='batchIds'){
      formValue.batchIds = res.data.batchIds.split(',')
    }
  })
  spinShow.value = false
}
watch(
  () => route,
  () => {
    if (route.name == 'DonationCertificateEdit') {
      getDispatchInfo()
    }
  },
  { deep: true, immediate: true }
)
onMounted(() => {
  getFunction()
  getFunctionCer()
})
</script>

<style scoped lang="scss">
@mixin CommonFont {
  font-size: 16rem;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.85);
}

.commonWidth {
  width: 360rem;
}

.main {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: hidden;

  .topTitle {
    width: 100%;
    height: 64rem;
    border-bottom: 1px solid #fff;
    padding: 20rem;
    margin-bottom: 20rem;
    @include CommonFont;
  }

  .form_content {
    width: 100%;
    height: 100%;
    padding: 20rem 20rem 0;

    .content {
      display: flex;
      align-items: center;
      flex-direction: column;
      width: 100%;
      height: 100%;
      padding: 18rem 33rem 120rem;
      overflow-y: scroll;
      background-color: #ebeceb;

      .scope {
        width: 360rem;
        height: 130rem;
        background: #e1e1e1;
        margin-bottom: 25rem;
      }
    }
  }
}

.content::-webkit-scrollbar {
  display: none;
}

:deep(.n-spin-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-content) {
  width: 100%;
  height: 100%;
}

:deep(.n-spin-content) {
  width: 100%;
  height: 100%;
}
</style>
